package com.lqw.wechat.service.follower.impl;

import com.lqw.wechat.dao.FollowerMapper;
import com.lqw.wechat.entity.Follower;
import com.lqw.wechat.service.follower.FollowerService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * Created by luqiwen on 2017/8/3.
 */
@Service
public class FollowerServiceImpl implements FollowerService{

    private static final Logger LOGGER= LoggerFactory.getLogger(FollowerServiceImpl.class);

    @Autowired
    private FollowerMapper followerMapper;

    @Override
    public void subscribe(String openId, long followTime) {
        if(StringUtils.isEmpty(openId) || followTime==0){
            LOGGER.info("保存关注者失败，openId为空");
            return;
        }
        Follower follower=followerMapper.getFollowerByOpenId(openId);
        if(follower==null) {
            follower = new Follower();
            follower.setOpenid(openId);
            follower.setFollowTime(followTime);
            follower.setCreateTime(new Date());
            followerMapper.insert(follower);
            return;
        }

        if(follower.getValid()==0){
            follower.setValid((byte)1);
            follower.setFollowTime(followTime);
            follower.setUpdateTime(new Date());
            followerMapper.updateByPrimaryKey(follower);
        }

    }

    @Override
    public void unSubscribe(String openId) {
        if(StringUtils.isEmpty(openId)){
            LOGGER.info("保存关注者失败，openId为空");
            return;
        }
        Follower follower=followerMapper.getFollowerByOpenId(openId);
        if(follower!=null) {
            follower.setValid((byte) 0);
            follower.setUpdateTime(new Date());
            followerMapper.updateByPrimaryKey(follower);
            return;
        }
    }
}
